package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public abstract class BaseServlet extends HttpServlet{

	private static final long serialVersionUID = -6203625286536278208L;
	
	protected HttpServletRequest request;
	
	private void setRequest(HttpServletRequest request) throws Exception{
		request.setCharacterEncoding("UTF-8");
		this.request = request;
	}
	
	protected HttpServletResponse response;
	
	private void setResponse(HttpServletResponse response) throws Exception {
		response.setCharacterEncoding("UTF-8");
		this.response = response;
	}
	
	protected HttpServletResponse decorateResponse() {
		response.setContentType("text/html");
		return response;
	}
	
	protected HttpSession getSession() throws Exception{
		return request.getSession(); 
	}
	
	protected PrintWriter getWriter() throws Exception{
		return response.getWriter();
	}
	
	protected void closeWriter(PrintWriter out) throws Exception{
		if(out!=null){
			out.flush();
			out.close();
		}
	}
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			setRequest(req);
			setResponse(resp);
			service();
		} catch (Exception e) {
			e.printStackTrace();
			/*throw new ServletException(e);*/
		}
	}
	
	//继承此类的子类servlet只需重写该方法即可
	protected abstract void service() throws Exception;
	
}

